#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
__auth__ = 'mason'

from email.utils import formatdate
import requests, json, time, datetime
import auth
from grafanaCallBack.conf import setting

appLicationReponame = setting.configs['applicationReponame']
nginxAccessReponame = setting.configs['nginxAccessReponame']

'''
PartialSearch请求说明
适用于非永久存储的repo且具有时间字段的repo查询,该接口针对超大规模日志进行优化。
注：此接口最多只能读取1万条日志
https://developer.qiniu.com/insight/api/5240/query-log
'''
accessKey = setting.configs['accessKey']
secretKey = setting.configs['secretKey']


def apiPartialSearch(repoName,queryCondition):
    endPoint = 'https://nb-insight.qiniuapi.com'
    resource = '/v5/repos/' + repoName + '/s'
    authorizationObj = auth.Auth(accessKey, secretKey)
    authorization = authorizationObj.sign_request('POST', resource)
    url = endPoint + '/v5/repos/' + repoName + '/s'

    headers = {'Content-Type':'application/json',
               'Date':formatdate(None, usegmt=True),
               'resource':resource,
               'qiniu-headers':'',
               'Authorization':'Pandora '+authorization}

    result = requests.post(url, headers=headers, data=json.dumps(queryCondition))
    if result.status_code != 200:
        print '从七牛云获取日志出错，请联系管理员进行检查,返回状态码为:%s', result.status_code
    else:
        resultObj = json.loads(result.text)
        print '从七牛云返回的数据为(摘要信息)'
        for k,v in resultObj.items():
            if k != 'hit':
                print k,'===>',v
        return resultObj




#if __name__ == '__main__':
    # packageAbsLogPath = '/APP/web/logs/cjds-coupon-service/log.log'
    # packageAbsLogPath = '/APP/web/logs/emall-item-gateway/info.log'
    # queryString = 'datasource:"%s" AND loglevel:"ERROR"' % (packageAbsLogPath)
    # resultObj = apiPartialSearch(appLicationReponame, )
    # for k,v in resultObj.items():
    #     print (k,'===>',v)
    #
    # if resultObj['total'] > 0:
    #     print '*'*50
    #     for index, value in enumerate(resultObj['hits']):
    #         print(index,'==>',value)


